<template>
  <audio ref="audio" @timeupdate.passive="watchPlay" :volume="volume">
    <source :src="source" type="audio/mp3" />
    <source :src="source1" type="audio/mp3" />
  </audio>
</template>

<script>
import { ref, computed, onMounted } from "vue";
import { useStore } from "vuex";
import audioChangePlayTime from "@/components/globalAudio/Mixin/audioChangePlayTime.js";
import audioCutSongMixin from "@/components/globalAudio/Mixin/audioCutSongMixin.js";
import audioOrderPlayMixin from "@/components/globalAudio/Mixin/audioOrderPlayMixin.js";

export default {
  name: "GlobalAudio",
  setup() {
    //  控制播放与暂停

    //  获取audio 标签
    const audio = ref(null);
    const store = useStore();
    const endtimePlay = audioOrderPlayMixin(audio);
    onMounted(() => {
      //  控制音频播放与暂停
      // auidoPlayAndPause(audio);
      //  改变音乐的播放时间
      audioChangePlayTime(audio);
      store.commit("PlaySong/changeAudioElement", audio.value);
    });
    const p = audioCutSongMixin(audio);
    const source = computed(() =>
      store.state.PlaySong.presentSong === null
        ? null
        : store.state.PlaySong.presentSong.$_songUrl
    );
    const source1 = computed(() =>
      store.state.PlaySong.presentSong === null
        ? null
        : `https://music.163.com/song/media/outer/url?id=${store.state.PlaySong.presentSong.id}.mp3`
    );
    const playingNumberTimeFlag = computed(
      () => store.state.PlaySong.playingNumberTimeFlag
    );
    //  获取vuex

    //  当歌曲播放时,自动调整进度条
    function watchPlay() {
      const data = (audio.value.currentTime / audio.value.duration).toFixed(7);
      //  store.state.ProgressBar.flagProgressBar 为true 此时进度条不随播放时间更新。 为false时 进度条与播放时间同步更新
      if (store.state.ProgressBar.flagProgressBar) {
        //  当鼠标按下移动为时,将音乐的播放时间存放在临时值里面
        store.commit("ProgressBar/temporaryTime", data);
      } else {
        //  让进度条随着播放时间 同步更新
        store.commit("ProgressBar/playTimeProgressBar", data);
        //  让页面显示当前播放的时间
        store.commit("PlaySong/ChangePlayingTime", audio.value.currentTime);
      }
      //  当鼠标移动时关闭
      if (playingNumberTimeFlag.value) {
        store.commit("PlaySong/changePlayingNumberTime", audio.value.currentTime);
      }

      // if (audio.value.buffered.end(0) != store.state.ProgressBar.buffered) {
      //   store.commit(
      //     "ProgressBar/changeBuffered",
      //     audio.value.buffered.end(0) / audio.value.duration
      //   );
      // }

      audio.value.ended && endtimePlay();
    }

    //  获取音量
    const volume = computed(() => store.getters["SongVolume/volume"]);

    return {
      watchPlay,
      audio,
      volume,
      ...p,
      source,
      source1,

      // presentSong,
    };
  },
};
</script>
